<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use fast\Form;
/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => &$v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                $v->group_txt =$v->group_id? implode(',', model('UserGroup')->where('id','in', $v->group_id)->column('name')) : '';
                $v->level_txt = $v->level? model('UserLevel')->where('id', $v->level)->value('name') : '';
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post('row/a');
            
            $params['group_id'] = implode(',', $params['group_id']);
            $area = explode('/',$params['area']);
            $params['district'] = $area[2];
            $params['city'] = $area[1];
            $params['province'] = $area[0];
            if(!empty($params['saidao'])){
                $params['saidao'] = implode(',',array_map(function( $subArray) {
                    return reset( $subArray); // 获取子数组的第一个值
                },  $params['saidao']));

            }
            if(!empty($params['ziyuan'])){
                $params['ziyuan'] = implode(',',array_map(function( $subArray) {
                    return reset( $subArray); // 获取子数组的第一个值
                },  $params['ziyuan']));
            }
            if(!empty($params['xuyao'])){
                $params['xuyao'] = implode(',',array_map(function( $subArray) {
                    return reset( $subArray); // 获取子数组的第一个值
                },  $params['xuyao']));
            }
            $result = $row->allowField(true)->save($params);
            if ($result !== false) {
                $this->success();
            } else {
                $this->error($row->getError());
            }
            
        }
       
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row['area'] = $row['district']?$row['province'].'/'.$row['city'].'/'.$row['district']:"";
        $this->view->assign('groupList', Form::selectpickers('row[group_id][]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker', 'data-live-search' => 'true']));
        $this->view->assign('userlevel', Form::selectpicker('row[level]', array_merge(['0'=>'未购买会员'], model('UserLevel')->column('id,name')), $row['level'], ['class' => 'form-control selectpicker', 'data-live-search' => 'true']));
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

}
